package com.netcracker.educenter.filestorage.servlets.files.deleting;

import com.netcracker.educenter.filestorage.beans.UserStatelessBeanLocal;
import com.netcracker.educenter.filestorage.configurator.Configurator;
import org.apache.log4j.Logger;

import javax.ejb.EJB;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

@WebServlet(urlPatterns = "/user/Delete")
public class DeleteFileServlet extends HttpServlet {

    private static final Logger log = Logger.getLogger(DeleteFileServlet.class.getName());
    private static final String FILES_LIST_JSP_URL = Configurator.getConfigurator().getFileslistPageUrl();
    private static final String JNDI_BEAN_NAME = "java:global/fileStorage-1.0-SNAPSHOT/UserStatelessBean";
    @EJB
    UserStatelessBeanLocal userStatelessBeanLocal;

    @Override
    public void service(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {

        String queryString = URLDecoder.decode(request.getQueryString(), "Cp1251");
        String fileName = queryString.substring(queryString.indexOf("=") + 1);

        String userName = (String)request.getSession().getAttribute("authorized_user");

        try {
            InitialContext initialContext = new InitialContext();
            userStatelessBeanLocal = (UserStatelessBeanLocal)initialContext.lookup(JNDI_BEAN_NAME);

            userStatelessBeanLocal.deleteFile(fileName, userName);

        } catch (NamingException e) {
            log.error("Cannot find bean", e);
        }

        try {
            response.sendRedirect(request.getContextPath() + FILES_LIST_JSP_URL);
        } catch (IOException e) {
            log.error("Cannot refresh page", e);
        }
    }
}
